package router

import (
	"strconv"

	"gitee.com/xxhsjp/x-core/conf"
	_ "gitee.com/xxhsjp/x-core/logger"
	"gitee.com/xxhsjp/x-core/model"
	mw "gitee.com/xxhsjp/x-web/middlewares"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
)

var config = &model.ServerConfig{Port: 8080, Name: "0.0.0.0"}

func New() *Router {
	return &Router{ginEngine()}
}

type Router struct {
	*gin.Engine
}

func (r *Router) RunServer() error {
	return r.Run(config.Name + ":" + strconv.Itoa(config.Port))
}

func ginEngine() *gin.Engine {
	bindDefaultConfig()
	proxy := config.Proxy
	if config.Mode == "release" {
		gin.SetMode(gin.ReleaseMode)
	}
	router := gin.New()
	if len(proxy) > 0 {
		router.SetTrustedProxies(proxy)
	} else {
		router.SetTrustedProxies(nil)
	}

	router.Use(gin.Recovery())
	router.Use(mw.UUID())
	router.Use(mw.Access())
	return router
}

func bindDefaultConfig() {
	viper := conf.Wrapper
	viper.SetDefault("server.ignoreRespLogExps", []string{})
	viper.UnmarshalKey("server", config)
	logrus.Infof("server config: %+v", config)
}
